package ynu.edu.achitectureclass.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ynu.edu.achitectureclass.Factory.SensorServiceFactory;
import ynu.edu.achitectureclass.service.SensorService;

import java.util.List;

@RestController
public class BaseSensorController<T> {

    @Autowired
    private SensorServiceFactory sensorServiceFactory;

    @GetMapping("/token")
    public String getAccessToken() {
        return sensorServiceFactory.getAccessToken();
    }

    @PostMapping("/data")
    public ResponseEntity<String> getSoilData(@RequestParam String sensorType) {
        SensorService<?> service = sensorServiceFactory.getService(sensorType);
        try {
            service.fetchAndStoreSoilData(sensorType);
            return ResponseEntity.ok("Soil data successfully fetched and stored.");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Error fetching or storing soil data: " + e.getMessage());
        }
    }

    @GetMapping("/latest")
    public ResponseEntity<T> getLatestData(@RequestParam String sensorType) {
        try {
            SensorService<T> service = (SensorService<T>) sensorServiceFactory.getService(sensorType);
            T latestData = service.getLatestData();
            return ResponseEntity.ok(latestData);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/all")
    public ResponseEntity<List<T>> getAllData(@RequestParam String sensorType) {
        try {
            SensorService<T> service = (SensorService<T>) sensorServiceFactory.getService(sensorType);
            List<T> allData = service.getAllData();
            return ResponseEntity.ok(allData);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }
}